package com.whcoding.base.project.exception;

import com.whcoding.base.project.common.api.BaseResultVO;
import com.whcoding.base.project.common.api.ResultStatusEnum;
import com.whcoding.base.project.controller.DeptController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @program: spring-boot-learning
 * @description: @Validated参数验证 失败信息返回状态包装
 * @author: whcoding
 * @create: 2022-06-30 11:08
 **/
@RestControllerAdvice
public class ControllerExceptionAdvice {

	private static final Logger log = LoggerFactory.getLogger(ControllerExceptionAdvice.class);

	/**
	 * 参考文档: https://mp.weixin.qq.com/s/ANJ0DV9wyZA-mBdgDuiufw
	 *
	 * 统一封装异常  @Validated 验证处理
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler({MethodArgumentNotValidException.class})
	public BaseResultVO MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
		// 从异常对象中拿到ObjectError对象
		ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
		return BaseResultVO.fail(ResultStatusEnum.VALIDATE_ERROR,
				objectError.getDefaultMessage());
	}

	/***
	 * 自定义异常返回
	 * @param e
	 * @return
	 */
	@ExceptionHandler(APIException.class)
	public BaseResultVO APIExceptionHandler(APIException e) {
		return BaseResultVO.fail(e.getCode(), e.getMessage(), e.getMessage());
	}

}
